import { OSS_TOKEN } from '@/api/cms';
// import { REGION_LIST } from '@/api/home';
import {CONFIG_RULE_INFO} from '@/api/mine';

export async function getOssParams(http) {
  try {
    const response = await http.get(OSS_TOKEN);
    if (response.data) {
      return response.data; // 返回 OSS 参数
    } else {
      throw new Error('获取OSS参数失败');
    }
  } catch (error) {
    console.error('获取OSS参数错误:', error);
    throw error;
  }
}

export async function uploadImage(file, ossParams, voucherUrls) {
  try {
    // 创建FormData对象
    const formData = new FormData();
	
	

    // 生成带时间戳的文件名
    const timestamp = Date.now();
    const fileNameWithTimestamp = `${file.file.name.split('.').slice(0, -1).join('.')}_${timestamp}.${file.file.name.split('.').pop()}`;
	

    formData.append('key', `${ossParams.path}/${fileNameWithTimestamp}`); // 使用带时间戳的文件名
    formData.append('OSSAccessKeyId', ossParams.access_key_id);
    formData.append('policy', ossParams.policy);
    formData.append('Signature', ossParams.signature);
    formData.append('callback', ossParams.callback);
    formData.append('file', file.file);
    formData.append('success_action_status', 200);

    // 发送上传请求
    const response = await fetch(ossParams.domain, {
      method: 'POST',
      body: formData
    });

    if (response.status == 200) {
      const url = `${ossParams.domain}/${ossParams.path}/${fileNameWithTimestamp}`; // 使用带时间戳的文件名
      // 查找并更新现有项
      // const index = voucherUrls.findIndex(item => item.file.name === file.file.name);
	  
	  const index  = voucherUrls.findIndex((item) => {
		  if(item.file && item.file.name) {
			  return item.file.name === file.file.name
		  }else {
			  return false
		  }
	  })
	  
      if (index !== -1) {
        voucherUrls[index].url = url;
        voucherUrls[index].status = 'success';
      }
    }
  } catch (error) {
    console.error('上传错误:', error);
    // 标记上传失败
    const index = voucherUrls.findIndex(item => item.file.name === file.file.name);
    if (index !== -1) {
      voucherUrls[index].status = 'failed';
    }
  }
}
  
  export function uploadDelete(file, voucherUrls) {
    // 删除指定文件
    return voucherUrls.filter(item => item.url !== file.url);
  }

  export async function getExampleList(http,key) {
        // 查看示例
        let params={
          key: key,
        }
        try {
          const response = await http.get(CONFIG_RULE_INFO,{params:params});
          if (response.data) {
            let params=response.data
            return params;
          } else {
            throw new Error('获取失败');
          }
        } catch (error) {
          console.error('获取错误:', error);
          throw error;
        }

    }
    export const setImageUrl = (sourceUrl) => (sourceUrl === '' ||sourceUrl === undefined  ? [] : [{ url: sourceUrl }]);
    export const getImageUrl = (data) => (data === undefined ? '' : data[0]?.url || '');